package com.aube.plugin.gallery;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.aube.plugin.gallery.preview.GalleryItem;
import com.aube.plugin.gallery.preview.GalleryListView;
import com.aube.plugin.gallery.preview.GalleryPreviewLayout;
import com.aube.plugin.gallery.preview.ImagePreviewActivityHelper;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.dynamicload.BlurViewDecorator;
import com.huyn.baseframework.dynamicload.DLBridge;
import com.huyn.baseframework.dynamicload.DynamicLoaderHelper;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.CategorySimple;
import com.huyn.baseframework.utils.BitmapUtils;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.SysUtil;
import com.ryg.dynamicload.DLBasePluginFragmentActivity;

import java.util.HashMap;
import java.util.List;

/**
 * Created by huyaonan on 16/8/29.
 */
public class GalleryListActivity extends DLBasePluginFragmentActivity {
    public static final String GALLERY = "GALLERY";

    private static final int MAX_NUM  = 20;

    private CategorySimple mCate;

    private BlurViewDecorator mBlurview, mBlurTop;

    private ParallaxGalleryTopBarLayout mParallaxTop;

    private View mBlurMask;
    private ImageView mBg, mHead;
    private ImageView mBgReal, mHeadReal;

    private GalleryListView mGallery;

    private FrameLayout mBlurBgLayout;

    private GalleryPreviewLayout mGalleryPreviewLayout;

    private int mLastScrollY = 0;
    private int targetHeight;
    private int statusHeight = 0;
    private int topbarheight = 200;

    private boolean mDataLoadFinished = false;
    private boolean mDataLoading = false;
    private String mLastId="";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout_character_gallery);

        Intent intent = getIntent();
        mCate = (CategorySimple) intent.getSerializableExtra(GALLERY);

        mBg = (ImageView) findViewById(R.id.bg);
        mHead = (ImageView) findViewById(R.id.detail_header);
        mBgReal = (ImageView) findViewById(R.id.bg_real);
        mHeadReal = (ImageView) findViewById(R.id.detail_header_real);

        mBlurMask = findViewById(R.id.blur_mask);

        mGallery = (GalleryListView) findViewById(R.id.detail_list);

        mGallery.setOnScrollListener(new GalleryListView.OnScrollListener() {
            @Override
            public void onScrolled(int y) {
                if (y == mLastScrollY)
                    return;
                mLastScrollY = y;
                if (y >= targetHeight - topbarheight - statusHeight) {
                    mParallaxTop.updateTitleOffset(targetHeight - topbarheight - statusHeight);
                } else {
                    mParallaxTop.updateTitleOffset(y);
                }

                int targetY = targetHeight - y;
                mBlurview.setTranslationY(targetY < 0 ? 0 : targetY);
                mBlurview.invalidate();

                mBlurTop.setTranslationY(-y);
                float alpha = 0;
                if (y > targetHeight - topbarheight - statusHeight) {
                    alpha = 1f;
                } else {
                    alpha = y * 1f / (targetHeight - topbarheight - statusHeight);
                }
                mBlurTop.setAlpha(alpha);
                mBlurTop.invalidate();

                mBlurMask.setTranslationY(targetY < 0 ? -targetHeight : -y);
                mBlurMask.setAlpha(1 - alpha);
            }

            @Override
            public void onScrollToEnd() {
                onLoadMore(false);
            }

        });

        mBlurBgLayout = (FrameLayout) findViewById(R.id.blur_bg_layout);
        try {
            mBlurview = getBlurView(false);
            mBlurview.setOverlayColor(0xcc202020);
            mBlurBgLayout.addView(mBlurview);
            View view = findViewById(R.id.bg_layout);
            mBlurview.setBlurredView(view);

            mBlurTop = getBlurView(false);
            mBlurTop.setOverlayColor(0xcc202020);
            mBlurBgLayout.addView(mBlurTop);
            mBlurTop.setBlurredView(view);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mParallaxTop = (ParallaxGalleryTopBarLayout) findViewById(R.id.parallax_topbar);

        statusHeight = SysUtil.getStatusHeight(that);
        topbarheight = getResources().getDimensionPixelOffset(R.dimen.actionbar_height);
        targetHeight = getResources().getDimensionPixelOffset(R.dimen.category_list_head_height);

        RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) mParallaxTop.getLayoutParams();
        params2.height = targetHeight;
        mParallaxTop.setTopbarHeight(topbarheight);
        mParallaxTop.updateTitle(mCate.modelName);

        mBlurview.setTranslationY(targetHeight);

        FrameLayout.LayoutParams topParams = (FrameLayout.LayoutParams) mBlurTop.getLayoutParams();
        topParams.height = targetHeight;

        RelativeLayout.LayoutParams params3 = (RelativeLayout.LayoutParams) mBlurMask.getLayoutParams();
        params3.height = targetHeight;

        GradientDrawable drawable = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, new int[]{0x884e4c4c, 0x00000000});
        drawable.setShape(GradientDrawable.RECTANGLE);
        drawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);
        mBlurMask.setBackgroundDrawable(drawable);

        mBlurMask.setAlpha(1f);
        mBlurTop.setAlpha(0f);

        mGallery.setPadding(0, topbarheight+statusHeight, 0, 0);
        mGallery.setItemBg(BitmapFactory.decodeResource(getResources(), R.drawable.bk_default));

        mBg.setImageResource(R.drawable.bk_default);
        mBgReal.setImageResource(R.drawable.bk_default);
        mHead.setImageResource(R.drawable.bk_default);
        mHeadReal.setImageResource(R.drawable.bk_default);

        getData(false);
    }

    private void onLoadMore(boolean fromPreview) {
        if(mDataLoading || mDataLoadFinished)
            return;
        mDataLoading = true;
        getData(fromPreview);
    }

    /**
     * 模块内容接口
     * templateCode(index | actor)
     * ostype(iphone|android)
     * modelCode（template接口中获取）
     * relatedId（有就传，比如嘉宾）
     * lastId（分页用，第一次可不传，当前页最后一个id）
     * maxnum（一页最大条数）
     */
    public void getData(final boolean fromPreview) {
        HashMap<String, String> params = new HashMap<>();
        params.put("method", "com.aube.app.model.data");
        params.put("templateCode", mCate.templateType);
        params.put("modelCode", mCate.modelCode);
        params.put("relatedId", mCate.relatedId);
        if(StringUtils.isNotBlank(mLastId))
            params.put("lastId", mLastId);
        params.put("maxnum", MAX_NUM + "");
        params.put("subModelCode", mCate.subModelCode);
        exeHttpRequest(params, CategoryListModel.class, null, new Response.Listener<CategoryListModel>() {
            @Override
            public void onResponse(CategoryListModel response) {
                mDataLoading = false;
                if(response == null || !response.success())
                    return;
                setupData(response, fromPreview);
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                mDataLoading = false;
            }

            @Override
            public void onStart() {
                mDataLoading = true;
            }
        });
    }

    private void setupData(CategoryListModel model, boolean fromPreview) {
        if(model.data == null) {
            return;
        }
        List<Object> contents = null;
        for(CategoryImp category : model.data) {
            if("modelHead".equalsIgnoreCase(category.modelCode)) {
                ImageLoader.getInstance(that).preloadBitmap(category.headPic.picurl, new ImageLoader.IPreloadCallback<Bitmap>() {
                    @Override
                    public void onSuccess(Bitmap bitmap) {
                        mBgReal.setImageBitmap(bitmap);
                        mHeadReal.setImageBitmap(bitmap);
                        final ValueAnimator anim = ValueAnimator.ofFloat(1, 0);
                        anim.setDuration(500);
                        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator animation) {
                                float alpha = (float) animation.getAnimatedValue();
                                mBg.setAlpha(alpha);
                                mHead.setAlpha(alpha);
                                mBlurview.invalidate();
                            }
                        });
                        anim.addListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                mBg.setVisibility(View.GONE);
                                mHead.setVisibility(View.GONE);
                            }
                        });
                        anim.start();
                    }

                    @Override
                    public void onFail() {

                    }
                });
            } else {
                if(StringUtils.isBlank(mCate.modelName)) {
                    mCate.modelName = category.modelName;
                    mParallaxTop.updateTitle(mCate.modelName);
                }

                contents = category.dataDetail;
                mLastId = category.lastid;
//                if(contents.size() < MAX_NUM)
//                    mDataLoadFinished = true;
                if(StringUtils.isBlank(mLastId))
                    mDataLoadFinished = true;
                //sax and setup
                List<PictureImp> mContent = PictureImp.parse(contents);
                if(mGallery.getChildCount() > 0)
                    appendData(mContent, fromPreview);
                else
                    setupData(mContent, targetHeight);
            }
        }
    }

    private void setupData(List<PictureImp> mContent, int topHeight) {
        if(mContent == null || mContent.size() == 0)
            return;

        mGallery.addView(new View(that), 0, new ViewGroup.LayoutParams(SysUtil.getAbsoluteScreenWidth(that), topHeight));

        mGallery.addChildView(mContent, topHeight, true);

        mGallery.setOnItemClickListener(new GalleryListView.OnChildClickListener() {

            @Override
            public void OnItemClickListener(GalleryItem view, List<PictureImp> pictures, int position) {
                injectAndOpenGalleryPreview(view.getImageView(), pictures, position);
            }
        });
    }

    private void injectAndOpenGalleryPreview(ImageView view, List<PictureImp> pictures, int position) {
        if(mGalleryPreviewLayout == null) {
            mGalleryPreviewLayout = (GalleryPreviewLayout) DynamicLoaderHelper.loadTargetLayout(that, mPluginPackage, GalleryPreviewLayout.class.getName());
            mGalleryPreviewLayout.fillData(mCate.relatedId);
            mGalleryPreviewLayout.registLoadListener(new GalleryPreviewLayout.OnLoadMoreListener() {
                @Override
                public void shouldLoadMore() {
                    onLoadMore(true);
                }
            });

            addContentView(mGalleryPreviewLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

            if(that instanceof DLBridge) {
                ((DLBridge) that).registToReceiveKeyBackGroup(mGalleryPreviewLayout);
                mGalleryPreviewLayout.setDLBridge((DLBridge) that);
            }
        }

        Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(view);
        ImagePreviewActivityHelper.startPreivew(mGalleryPreviewLayout, view, pictures, bitmap, position, ImagePreviewActivityHelper.LOACTION_TYPE_MOVIEPOSTER_LIST);
    }

    private void appendData(List<PictureImp> mContent, boolean fromPreview) {
        if(mContent == null || mContent.size() == 0)
            return;

        mGallery.addChildView(mContent, 0, false);
//        mGallery.loadPicture(mGallery.getChildCount(), 10);

        if(fromPreview && mGalleryPreviewLayout != null) {
            mGalleryPreviewLayout.appendData(mContent);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mGallery != null)
            mGallery.onDestroy();
    }
}
